package com.ysx.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysx.common.utils.AppJwtUtil;
import com.ysx.exception.ToutiaoException;
import com.ysx.wemedia.pojo.WmUser;
import com.ysx.wemedia.mapper.WmUserMapper;
import com.ysx.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2021-09-08
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;

    //根据用户id查询自媒体账号
    @Override
    public WmUser selectByUserId(Integer userId) {
        QueryWrapper<WmUser> wmUserQueryWrapper = new QueryWrapper<>();
        wmUserQueryWrapper.eq("ap_user_id", userId);
        return wmUserMapper.selectOne(wmUserQueryWrapper);
    }
    //登录自媒体系统成功签发token令牌
    @Override
    public Map<String, Object> loginSystemReturnToken(WmUser wmUser) throws ToutiaoException {
        //思路：
        //1,判断对象输入的用户名或密码是否为Null
        String username = wmUser.getName();
        String password = wmUser.getPassword();
        if (username == null || password == null) {
            //2,为null 抛出自定义异常信息
            throw new ToutiaoException("您的账号密码不能为空");
        }
        //3,不为null 根据用户名查询数据库
        QueryWrapper<WmUser> adUserQueryWrapper = new QueryWrapper<>();
        adUserQueryWrapper.eq("name",username);
        WmUser wmUserDB = wmUserMapper.selectOne(adUserQueryWrapper);
        //4,判断返回的对象是否为Null
        if(ObjectUtils.isEmpty(wmUserDB)){
            throw new ToutiaoException("您输入的账号或密码有误");
        }
        //6,根据数据库查询的密码 跟用户输入的密码 进行校验(加盐加密)
        String salt = wmUserDB.getSalt();
        String saltPassword = password + salt;
        String passwordUser = DigestUtils.md5DigestAsHex(saltPassword.getBytes());//用户的密文
        if(!passwordUser.equals(wmUserDB.getPassword())){
            throw new ToutiaoException("您输入的账号或密码有误");
        }
        //7,封装数据
        String token = AppJwtUtil.createToken(Long.parseLong(wmUserDB.getId() + ""));
        Map<String,Object> hm=new HashMap<>();
        hm.put("token",token);
        return hm;
    }
}
